#include "open_file.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

open_file::open_file(const char *path)
{
    m_path= path;
    m_file_size = 0;
    m_buffer = NULL;
}

open_file::~open_file()
{
    if (fp)
        fclose(fp);
    
    if (m_buffer)
    {
        free(m_buffer);
        m_buffer = NULL;
    }
}

unsigned long open_file::get_file_size()
{
    return m_file_size;
}

char *open_file::get_file_buffer()
{
    struct stat st;
    if (stat(m_path.c_str(), &st) < 0)
    {
        return NULL;
    }

    m_buffer = (char *)malloc(st.st_size + 1);
    if (m_buffer == NULL)
        return 0;
    memset(m_buffer, 0, st.st_size + 1);
    fp = fopen(m_path.c_str(), "r");
    if (NULL == fp)
        return NULL;
    if (st.st_size != (off_t)fread((void *)m_buffer, 1, st.st_size, fp))
    {
        return NULL;
    }

    m_file_size = st.st_size;

    printf("bfu addr = %p\n", m_buffer);
    return m_buffer;
}

